package br.com.post.persistence;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.State;

public class StateDao {
	private static StateDao instance;
	/**
	 * Persiste estado no banco
	 * @param state
	 */
	public void createState(State state) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(state);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza o estado no banco
	 * @param state
	 */
	public void updateState(State state) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(state);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona um estado no banco de acordo com o id(long)
	 * @param state_id
	 * @return state
	 */
	public State selectState(long state_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		State state = (State)session.get(State.class,state_id);
		tx.commit();
		session.close();
		return state;
	}
	
	/**
	 * Deleta o estado de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove o estado selecionado
	 * @param state_id
	 */
	public void deleteState(long state_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		State state = selectState(state_id);
		session.delete(state);
		tx.commit();
		session.close();
	}

	public static StateDao getInstance() {
		if (instance==null)
			instance = new StateDao();
		return instance;
	}

	public static void setInstance(StateDao instance) {
		StateDao.instance = instance;
	}
	
}

